<template>
  <div>
    <!-- 查询 -->
    <div class="search">
      <a-row style="align-items: center; margin-bottom: 30px" :gutter="20">
        <a-col :span="3" :lg="3" :xs="6" :offset="1">
          <span class="user-title">订单状态:</span>
        </a-col>
        <a-col
          :span="2"
          :lg="2"
          :xs="4"
          class="user-status"
          v-for="(item, index) in orderStatus"
          :class="index == orderStatusAct ? 'user-status-act main-font-color' : ''"
          @click="chooseOrderStatus(item.status, index)"
          :key="item.status"
          ><div class="item-title">{{ item.title }}</div></a-col
        >
      </a-row>
      <a-form :model="form" :hideRequiredMark="true" :label-col="labelCol">
        <a-row :gutter="20">
          <a-col :span="5" :lg="5" :xs="12" :md="7">
            <a-form-item label="订单号">
              <a-input v-model:value="form.number" placeholder="请输入订单号"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="5" :lg="5" :xs="12">
            <a-form-item label="护士姓名">
              <a-input v-model:value="form.nurseName" placeholder="请输入护士姓名"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8" :lg="8" :xs="20">
            <a-form-item label="下单时间">
              <a-range-picker v-model:value="time" @change="selectTime" format="YYYY-MM-DD HH:mm:ss" />
            </a-form-item>
          </a-col>
          <a-col :span="2" :lg="2" :xs="5">
            <a-button type="primary" @click="search" class="d-a-center">搜索</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!--订单列表 -->
    <a-row style="margin: 20px 0" justify="end" :gutter="20" v-has="{ a: $route, b: 2 }">
      <a-col :span="4" style="text-align: right" :lg="4" :xs="8">
        <a-upload v-model:file-list="fileList" name="file" :customRequest="importOrder" :headers="headers" accept=".xls,xlsx">
          <a-button class="d-a-center">
            <upload-outlined></upload-outlined>
            导入订单
          </a-button>
        </a-upload>
      </a-col>
      <a-col :span="4" :lg="4" :xs="8">
        <a-button type="primary" @click="openModal('addOrderVisible')" class="d-a-center">新增订单</a-button>
      </a-col>
    </a-row>
    <a-table
      :columns="colums"
      :data-source="list"
      bordered
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      :row-selection="rowSelection"
      :scroll="{ y: 540, x: 'max-content' }"
    >
      <!-- 订单状态显示 -->
      <template #status="{ record }">
        <a-tag :color="orderListStatusColor(record.status)">
          {{ orderListStatus(record.status) }}
        </a-tag>
      </template>
      <template #price="{ record }">
        <span>{{ record.price ? record.price : '未结算' }}</span>
      </template>
      <template #nurseId="{ record }">
        <span>{{ record.nurseId ? record.nurseId : '未分配' }}</span>
      </template>
      <template #operation="{ record }">
        <!-- <a-button type="link" @click="deal(record)">修改</a-button> -->
        <a-button type="link" @click="look(record)" v-has="{ a: $route, b: 2 }">处理</a-button>
      </template>
    </a-table>

    <!-- 新增订单 -->
    <a-modal :visible="addOrderVisible" title="新增订单" @ok="addOrder" @cancel="closeModal('addOrderVisible')">
      <a-form :model="modalForm" :rules="rules" ref="modalFormRef">
        <a-form-item label="护士姓名" name="nurseName">
          <a-input placeholder="请输入护士姓名" v-model:value="modalForm.nurseName"></a-input>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 查看订单 -->
    <a-modal :visible="orderVisible" title="查看订单" :footer="null" @cancel="closeModal('orderVisible')">
      <a-form :label-col="labelCol">
        <a-form-item label="订单号"> {{ orderDetail.number }} </a-form-item>
        <a-form-item label="护士姓名">{{ orderDetail.nurseName }}</a-form-item>
        <a-form-item label="护士ID">{{ orderDetail.nurseId ? orderDetail.nurseId : '未分配' }}</a-form-item>
        <a-form-item label="订单状态">
          <a-tag :color="orderListStatusColor(orderDetail.status)">
            {{ orderListStatus(orderDetail.status) }}
          </a-tag>
        </a-form-item>
        <a-form-item label="下单时间">{{ orderDetail.createdAt }}</a-form-item>
        <a-form-item label="结算价格" v-if="orderDetail.status == 5">{{ orderDetail.price }}</a-form-item>
        <a-divider></a-divider>
        <a-row>
          <a-col :span="4" :offset="8" v-if="orderDetail.status == 2">
            <a-button type="primary" @click="openModal('divideNurseVisible')">分配护士</a-button>
          </a-col>
          <a-col :span="4" :offset="8" v-if="orderDetail.status == 4">
            <a-button type="primary" @click="openModal('savePriceVisible')">完成</a-button>
          </a-col>
          <!-- <a-col :span="4" :offset="4">
            <a-button type="primary" @click="closeModal('orderVisible')"
              >关闭</a-button
            >
          </a-col> -->
        </a-row>
      </a-form>
    </a-modal>

    <!-- 结算价格 -->
    <a-modal :visible="savePriceVisible" title="" :footer="null" @cancel="closeModal('savePriceVisible')">
      <div style="margin: 20px 40px">
        <a-form @finish="onFinish" :model="priceForm">
          <a-form-item label="结算价格" name="price" :rules="[{ required: true, message: '请输入结算价格!' }]">
            <a-input-number v-model:value="priceForm.price" placeholder="请选择结算价格" style="width: 200px" :min="0.01"></a-input-number>
          </a-form-item>
          <a-divider></a-divider>
          <a-form-item>
            <a-row>
              <a-col :span="4" :offset="8">
                <a-button type="primary" html-type="submit">保存</a-button>
              </a-col>
            </a-row>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>

    <!-- 修改订单状态 -->
    <a-modal :visible="editVisible" title="" :footer="null" @cancel="closeModal('editVisible')">
      <div style="margin: 20px 40px">
        <a-form :model="editForm" ref="editFormRef" :rules="rules1">
          <a-form-item label="订单状态" name="status">
            <a-select ref="select" v-model:value="editForm.status" @change="handleChange" placeholder="请选择订单状态">
              <a-select-option v-for="item in editOrderStatus" :value="item.status" :key="item.status">{{ item.title }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="结算金额" name="price">
            <a-input v-model:value="editForm.price" placeholder="请输入结算金额"></a-input>
          </a-form-item>
        </a-form>
      </div>
      <a-divider></a-divider>
      <a-row>
        <a-col :span="4" :offset="8">
          <a-button type="primary" @click="editSave">保存</a-button>
        </a-col>
        <a-col :span="4" :offset="3">
          <a-button type="primary" @click="closeModal('editVisible')">取消</a-button>
        </a-col>
      </a-row>
    </a-modal>

    <a-row>
      <a-col :span="5">
        <a-button type="info" @click="excleData" v-has="{ a: $route, b: 2 }">导出数据</a-button>
      </a-col>
    </a-row>

    <!-- 展示用户导入的数据 -->
    <a-modal :visible="importVisible" title="导入的护士数据" okText="确认导入" @cancel="closeModal('importVisible')" @ok="confirmImport">
      <a-table :dataSource="importDataList" :columns="columns1" />
    </a-modal>

    <!-- 分配护士 -->
    <divide-nurse
      v-if="divideNurseVisible"
      :visible="divideNurseVisible"
      :number="orderDetail.number"
      :offline="true"
      @closeModal="closeModal('divideNurseVisible')"
      @divideNurse="divideNurse"
    ></divide-nurse>
  </div>
</template>
<script>
import { reactive, ref, watch, computed, defineComponent, createVNode, toRefs } from 'vue'
import {
  CheckOutlined,
  EditOutlined,
  ArrowDownOutlined,
  ArrowUpOutlined,
  ExclamationCircleOutlined,
  EditTwoTone,
  DeleteTwoTone,
  UploadOutlined
} from '@ant-design/icons-vue'
import { message, Modal, modal } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import xlsx from 'xlsx' //这个最新版本的会报错最好装低版本本
import { selectAll, importExcel, saveOrUpdateOld } from '@/api/order/index'
import divideNurse from '@/views/order/components/DivideNurse'
import { useModal } from '@/hooks'

export default {
  setup() {
    const form = reactive({})
    const visible = ref(false)
    const data = reactive({
      loading: true,
      orderStatusAct: 0, //订单状态
      time: [], //订单时间
      modalForm: {},
      addOrderVisible: false,
      orderVisible: false,
      isEdit: 0,
      editVisible: false,
      editFormRef: '',
      editForm: {},
      modalFormRef: '',
      importDataList: [], //导入的数据是
      importVisible: false, //导入数据弹窗
      list: [],
      number: '', //订单编号
      orderDetail: {}, //订单详情
      divideNurseVisible: false,
      savePriceVisible: false, //结算价格弹窗
      priceForm: {}, //结算价格
      selectList: [] //选中的列表
    })
    const router = useRouter()
    // 分页器
    const page = reactive({
      current: 1,
      pageSize: 10,
      total: 0
    })

    // 订单状态列表
    const orderStatus = [
      { title: '全部', status: 0 },
      { title: '待分配', status: 2 },
      { title: '已分配', status: 4 },
      { title: '已完成', status: 5 }
    ]

    // 订单状态
    const orderListStatus = status => {
      let title = ''
      switch (status) {
        case 2:
          title = '待分配'
          break
        case 4:
          title = '已分配'
          break
        case 5:
          title = '已完成'
          break
        default:
          break
      }
      return title
    }
    // 样式
    const orderListStatusColor = status => {
      let color = ''
      switch (status) {
        case 2:
          color = 'error'
          break
        case 4:
          color = 'cyan'
          break
        case 5:
          color = 'success'
          break
        default:
          break
      }
      return color
    }

    const editOrderStatus = [
      { title: '已完成', status: 5 },
      { title: '已取消', status: 6 }
    ]
    const rules = {
      nurseName: [{ required: true, message: '请输入护士姓名', trigger: 'blur' }]
    }
    const rules1 = {
      price: [{ required: true, message: '请输入结算金额', trigger: 'blur' }],
      status: [{ required: true, message: '请输入结算金额' }]
    }

    const colums = [
      {
        title: '订单号',
        dataIndex: 'number',
        className: 'table',
        width: 150,
        fixed: 'left'
      },
      {
        title: '护士姓名',
        dataIndex: 'nurseName',
        className: 'table',
        slots: {
          customRender: 'sort'
        }
      },
      {
        title: '护士ID',
        dataIndex: 'nurseId',
        className: 'table',
        slots: {
          customRender: 'nurseId'
        }
      },
      {
        title: '结算金额',
        dataIndex: 'price',
        className: 'table',
        slots: {
          customRender: 'price'
        }
      },
      {
        title: '订单状态',
        dataIndex: 'status',
        className: 'table',
        slots: {
          customRender: 'status'
        }
      },
      {
        title: '下单时间',
        dataIndex: 'createdAt',
        className: 'table'
        // sorter: (a, b) => a.time - b.time,
      },
      {
        title: '操作',
        dataIndex: 'operation',
        className: 'table',
        fixed: 'right',
        width: 100,
        slots: {
          customRender: 'operation'
        }
      }
    ]
    const columns1 = [
      {
        title: '姓名',
        dataIndex: 'nurseName'
      }
    ]

    const chooseOrderStatus = (status, index) => {
      // console.log(status, index);
      data.orderStatusAct = index
      if (status == 0) {
        delete form['status']
        init()
      } else {
        form.status = status
        init()
      }
    }
    // 全选反选
    const rowSelection = ref({
      checkStrictly: false,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
        data.selectList = selectedRows
      },
      onSelect: (record, selected, selectedRows) => {
        // console.log(record, selected, selectedRows,'选择多项');
      },
      onSelectAll: async (selected, selectedRows, changeRows) => {
        // console.log(selected, selectedRows, changeRows,'全选操作');
        if (selected) {
          let obj = {
            pageNum: 1,
            pageSize: page.total, //一共多少页第一页请求多少数据……
            ...form
          }
          let res = await selectAll(obj)
          if (res.success) {
            data.selectList = res.object.records
          }
        }
      }
    })

    // 分页器
    const pagination = computed(() => ({
      current: page.current,
      pageSize: page.pageSize,
      pageSizeOptions: ['10', '20', '30'],
      showTotal: (total, range) => {
        return '共' + total + '条'
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true
    }))

    // 分页器改变的时候
    const handleTableChange = (pagination, filters, sorter) => {
      console.log(pagination, '当前分页')
      page.current = pagination.current
      page.pageSize = pagination.pageSize

      // 请求列表接口
      init()
    }
    const selectTime = (e, dateString) => {
      form.startTime = dateString[0]
      form.endTime = dateString[1]
    }

    // 导入订单--自定义请求数据
    const importOrder = (file, fileList) => {
      // console.log(file, "file----");
      let reader = new FileReader()
      reader.readAsBinaryString(file.file) //这个是file.file文件，可不是file……
      reader.onload = ev => {
        let res = ev.target.result
        const worker = xlsx.read(res, { type: 'binary' })
        // console.log(worker, "worker是----");

        // 这个是将数据进行一步拼接
        //  worker.Sheets[worker.SheetNames[0]]

        // 将返回的数据转换为json对象的数据
        reader = xlsx.utils.sheet_to_json(worker.Sheets[worker.SheetNames[0]])
        // console.log(reader, "reader-----");
        let arr = []
        for (let i = 0; i < reader.length; i++) {
          let sheetData = {
            nurseName: reader[i]['姓名']
          }
          arr.push(sheetData)
        }
        data.importVisible = true
        data.importDataList = arr
        // console.log(arr, "最后的数据是---");
      }
    }
    const confirmImport = async () => {
      let res = await importExcel(data.importDataList)
      if (res.success) {
        closeModal('importVisible')
        message.success('成功导入~')
        init()
      }
    }
    // 打开模态框
    const openModal = e => {
      data[e] = true
    }
    // 关闭模态框
    const closeModal = e => {
      data[e] = false
    }

    const search = () => {
      if (Object.keys(form).length == 0) {
        message.warning('请输入你要搜索的内容！！！')
        return
      }
      page.current = 1
      data.loading = true
      init()
    }

    // 结算价格
    const onFinish = async () => {
      let obj = JSON.parse(JSON.stringify(data.orderDetail))
      obj.price = data.priceForm.price
      delete obj['key']
      obj.status = 5
      console.log(data.orderDetail, obj)
      let res = await saveOrUpdateOld(obj)
      if (res.success) {
        message.success('已成功结算')
        closeModal('orderVisible')
        closeModal('savePriceVisible')
        data.priceForm = {}
        init()
      }
    }

    // 分配护士-护士ID
    const divideNurse = async key => {
      let obj = JSON.parse(JSON.stringify(data.orderDetail))
      obj.nurseId = key
      obj.status = 4 //已分配
      delete obj['key']
      console.log(obj, '分配的护士信息是')

      let res = await saveOrUpdateOld(obj)
      if (res.success) {
        message.success('分配成功')
        closeModal('divideNurseVisible')
        closeModal('orderVisible')
        init()
      } else {
      }
    }

    const addOrder = () => {
      data.modalFormRef.validate().then(async () => {
        let res = await saveOrUpdateOld(data.modalForm)
        if (res.success) {
          message.success('新增成功')
          data.addOrderVisible = false
          init()
        }
      })
    }
    const editSave = () => {
      data.editFormRef.validate().then(() => {})
    }

    // 导出数据
    const excleData = () => {
      // 未选中--默认导出所有的数据
      if (data.selectList.length == 0) {
        message.warning('请选择你要导出的订单')
        return
      }
      const { closeModal } = useModal.confirm({
        title: `确认导出${data.selectList.length}条数据吗?`,
        icon: createVNode(ExclamationCircleOutlined),
        onOk() {
          const { export_json_to_excel } = require('../../../excel/Export2Excel')
          // 表头
          const tHeader = ['订单号', '护士姓名', '结算金额', '订单状态', '下单时间']
          // 字段
          const fitlerVal = ['number', 'nurseName', 'price', 'status', 'createdAt']

          const res = data.selectList.map(v => fitlerVal.map(j => v[j]))

          export_json_to_excel(tHeader, res, '导出的数据是----')
          data.selectList = [] //置空 选中的取消
          init()
          closeModal()
        },

        class: 'test'
      })
    }

    // 处理订单
    const deal = e => {
      data.editVisible = true
    }

    // 查看订单
    const look = e => {
      data.orderDetail = e
      data.orderVisible = true
    }

    init()

    async function init() {
      let obj = {
        pageNum: page.current,
        pageSize: page.pageSize,
        // status: data.orderStatusAct, //订单状态
        ...form
      }
      let res = await selectAll(obj)
      if (res.success) {
        res.object.records.map(el => (el.key = el.number))
        data.list = res.object.records
        page.total = res.object.total
        data.loading = false
      }
    }

    return {
      form,
      colums,
      pagination,
      ...toRefs(data),
      orderStatus,
      chooseOrderStatus,
      handleTableChange,
      rowSelection,
      excleData,
      look,
      deal,
      visible,
      openModal,
      closeModal,
      search,
      labelCol: { style: { fontWeight: 'bold', width: '100px' } },
      rules,
      importOrder,
      addOrder,
      editOrderStatus,
      rules1,
      editSave,
      columns1,
      confirmImport,
      selectTime,
      orderListStatus,
      orderListStatusColor,
      divideNurse,
      onFinish
    }
  },

  components: {
    CheckOutlined,
    EditOutlined,
    ExclamationCircleOutlined,
    EditTwoTone,
    DeleteTwoTone,
    ArrowUpOutlined,
    ArrowDownOutlined,
    UploadOutlined,
    divideNurse
  }
}
</script>

<style scoped lang="less">
.search {
  background-color: #e6e6e6;
  margin-bottom: 20px;
  padding: 1.6rem;
  font-size: 1rem;
  .user-title {
    font-size: 1.5rem;
    font-weight: bold;
  }
  .user-status {
    text-align: center;
    padding: 5px 0;
    font-size: 1.25rem;
  }
  .user-status-act {
    width: 70%;
    .item-title {
      background-color: #2a9d8f;
      color: #fff;
      border-radius: 20rem;
    }
  }
}
</style>
